package com.sdy.sso.web.controller;

import com.sdy.auth.api.AuthApi;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.service.SsoService;
import com.sdy.sso.biz.constants.RedisConstants;
import com.sdy.mvc.controller.BaseController;
import com.sdy.common.model.Response;
import com.sdy.common.utils.EncodeUtil;
import com.sdy.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.security.KeyPair;
import java.util.Base64;

/**
 * Created by zzq on 2019/1/10.
 */
@Slf4j
@Controller
public class IndexController extends BaseController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private AuthApi authApi;
    @Value("${res.app.raw.code:}")
    private String appRawCode;

    @GetMapping("/")
    public String index(HttpServletRequest request) {
        UserInfo userInfo = ssoService.getUserInfo(request);
        if (userInfo == null) {
            return "redirect:/login/page";
        } else {
            String url = authApi.getDefaultAppUrl(appRawCode);
            return "redirect:" + url;
        }
    }

    @GetMapping("/publicKey")
    @ResponseBody
    public Response publicKey(HttpServletRequest request) throws Exception {
        KeyPair keyPair = EncodeUtil.rsaGenKeyPair();
        String publicKeyStr = new String(Base64.getEncoder().encode(keyPair.getPublic().getEncoded()));
        redisService.set(RedisConstants.REDIS_PREFIX + "privateKey_" + getUserId(request), Base64.getEncoder().encode(keyPair.getPrivate().getEncoded()));
        return Response.success(publicKeyStr);
    }

}
